package com.example.big_orange2.authorization.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.example.big_orange2.authorization.annotation.AuthIgnore;
import com.example.big_orange2.authorization.manager.TokenManager;
import com.example.big_orange2.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    TokenManager tokenManager;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuthIgnore annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        }else{
            return true;
        }

        //如果有@AuthIgnore注解，则不验证token，防止非法访问数据，访问数据需要带token
        if(annotation != null){
            return true;
        }

        //获取用户凭证
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isBlank(token)){
            Object obj = request.getAttribute("token");
            if(null!=obj){
                token=obj.toString();
            }
        }

        //token凭证为空
        if(StringUtils.isBlank(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //若redis中存在token(登录过)
        if(redisUtils.hasKey(token)){
            return true;
        }else{
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        /*
        User user= tokenManager.getUserInfoByToken(token);
        if(user==null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;

        }
        */

    }
}
